//分享官考核
import React from 'react'
import { Typography, Modal, InputNumber, message, Tag } from 'antd';
import TheTable from '@/components/TheTable'
import ThePagination from '@/components/ThePagination'
import TheQueryForm from '@/components/TheQueryForm';
import TheButton from '@/components/TheButton';
import { sharerAssessList, shareRewardsList, editShareCommissionRate } from '@/request/distribution/sharerAssess.js'
import moment from 'moment';
import store from "@/store/store"
import _ from 'lodash'
import Json2Excel from '@/utils/Json2Excel'
const { Title } = Typography;
// 获取当前年份和月份
const currentYear = moment().year();
const currentMonth = moment().month();
export default class SharerAssess extends React.Component {
  state = {
    searchOption: [
      { field: 'infoData', label: '会员信息', placeholder: '输入会员ID/会员昵称/会员手机号', type: 'Input', defaultValue: '' },
      {
        field: 'time', label: '时间', placeholder: '选择考核时间', type: 'DatePicker',
        picker: "month",
        otherConfig: {
          // disabledDate: (current) => {
          //   // 获取要选择的年份和月份
          //   const selectedYear = current.year();
          //   const selectedMonth = current.month();
          //   // 如果要选择的年份大于当前年份，禁用它
          //   if (selectedYear > currentYear) {
          //     return true;
          //   }
          //   // 如果要选择的年份等于当前年份，且要选择的月份大于当前月份，禁用它
          //   if (selectedYear === currentYear && selectedMonth >= currentMonth) {
          //     return true;
          //   }
          //   // 允许选择该日期
          //   return false;
          // }
        },
      },
    ],
    queryForm: {},
    columns: [
      {
        title: "会员ID",
        dataIndex: "memberId",
        key: "memberId",
      },
      {
        title: "用户昵称",
        dataIndex: "username",
        key: "username",
      },
      {
        title: "用户会员手机号",
        dataIndex: "memberMobile",
        key: "memberMobile",
        render: (text) => {
          var reg = /^(\d{3})\d{4}(\d{4})$/;
          if (text) {
            var memberMobile = text.toString().replace(reg, '$1****$2');
            return memberMobile;
          }
        }
      },
      {
        title: "有效下单人数",
        dataIndex: "orderNumber",
        key: "orderNumber",
        sorter: (a, b) => a.orderNumber - b.orderNumber,
        render: (text) => {
          return text ? text : '0'
        }
      },
      {
        title: "实付GMV",
        dataIndex: "gmv",
        key: "gmv",
        sorter: (a, b) => a.gmv - b.gmv,
        render: (text) => {
          return React.$transNum(text || 0, 2, -2)
        }
      },
      {
        title: "所生效的佣金比例",
        dataIndex: "commissionRate",
        key: "commissionRate",
        render: (text) => {
          return text ? text + '%' : '0%'
        }
      },
      {
        title: "上次修改时间",
        dataIndex: "updateTime",
        key: "updateTime",
        render: (text) => {
          return text ? text : '-'
        }
      },
      {
        title: "操作",
        fixed: 'right',
        render: (_, record) => {
          return <TheButton haspermi={['distribution:sharerAssess:editCommission']} disabled={!record.isUpCommissionRate} onClick={() => { this.editCommission(record.sharedById) }}>修改佣金比</TheButton>
        }
      },
    ],
    dataSource: [],// 月度评级列表数据
    pageData: {
      pageNo: 1,
      pageSize: 10
    },
    total: 0,
    month: '', //展示年月份
    isEditCommission: false,//修改佣金比例弹窗
    commissionColumns: [
      {
        title: "时间",
        render: (_, record) => {
          return <div>
            {`${record.toYear}年${record.toMonth}月`}{parseInt(record.settlementType) === 0 && <Tag color="gold">默认佣金比</Tag>}
          </div>
        }
      },
      {
        title: "佣金比例",
        dataIndex: "commissionRate",
        key: "commissionRate",
        render: (text, record) => {
          return record.isUpCommissionRate ? <InputNumber value={this.state.commissionValue} onChange={this.valueInput} min={0} max={100} precision={0} placeholder='请输入佣金比例' /> : text
        }
      },
    ], //修改佣金比列表头
    commissionDataSource: [], //佣金比列数据
    commissionValue: null,//佣金比例修改值
    submitLoading: false,//确认修改loading
    sharedById: '',//分享官id
    id: '',//佣金比例主键id
    canEdit: null, //可以修改的佣金比例数据
    exportBtnLoading: false,//导出按钮loading
    param:undefined,// 表格升序降序传参
  }
  componentDidMount() {
    let searchParams = store.getState().searchValue
    let { pageNo, pageSize, queryForm, pathName } = searchParams
    if (searchParams && pageNo && pathName == 'SharerAssess') {
      this.setState({
        queryForm, pageData: { pageNo, pageSize }
      }, () => {
        this.queryFormRef.onSetDefault({ ...queryForm })
        this.getData({ ...queryForm })
      })
    } else {
      this.getData()
    }
  }
  //分享官列表数据处理
  getData = async (values) => {
    let { pageData, queryForm,param } = this.state
    this.setState({
      queryForm: values === undefined ? queryForm : { ...values }
    }, async () => {
      let params = { ...pageData, queryForm: this.state.queryForm}
      store.dispatch({
        type: 'SaveSearchValues',
        data: { pathName: 'SharerAssess', ...params }
      })
      await sharerAssessList({ ...pageData, ...values,param  }).then(res => {
        if (res.code === 0 && res.data) {
          this.setState({
            dataSource: res.data.data.records,
            pageData: {
              pageNo: res.data.data.current,
              pageSize: res.data.data.size
            },
            total: res.data.data.total,
            month: res.data.month
          })
        }
      })
      this.setState({})
    })
  }
  //分页
  pageChange = (pageNo, pageSize) => {
    this.setState({
      pageData: {
        pageNo, pageSize
      }
    }, () => {
      this.getData(this.state.queryForm)
    })
  }
  //搜索
  onFormSearch(values) {
    let { year, month } = this.state
    if (values && !_.isEmpty(values.time)) {
      values.month = moment(values.time).format('YYYY-MM')
      delete values.time
    }
    this.setState({
      pageData: { pageNo: 1, pageSize: 10 }, year, month
    }, () => {
      this.getData(values)
    })
  }
  //搜索重置
  onReset() {
    this.setState({ queryForm: {} }, () => {
      this.pageChange(1, 10)
    })
  }
  //表格排序
  handleTableChange = (pagination, filters, sorter) => {
    let param = {}
    if (sorter && sorter.order) {
      param = {
        asc: sorter.order === 'ascend',
        orderBys: [
          {
            asc: sorter.order === 'ascend',
            key: sorter.field
          }
        ]
      }
    }else{
      param = undefined
    }
    this.setState({ param },()=>{
      this.getData(this.state.queryForm)
    })
    console.log(pagination, filters, sorter);
  }

  //打开修改佣金比例弹窗
  editCommission = (sharedById) => {
    this.setState({ isEditCommission: true, sharedById }, async () => {
      await shareRewardsList({ sharedById }).then(res => {
        if (res.code === 0) {
          let canEdit = res.data.find(item => item.isUpCommissionRate) //可以修改的佣金比例数据
          let id = canEdit ? canEdit.id : null // 修改的佣金id
          let commissionValue = canEdit ? canEdit.commissionRate : null
          this.setState({ commissionDataSource: res.data, canEdit, id, commissionValue })
        }
      })
    })
  }
  // 佣金比例输入的值
  valueInput = (e) => {
    this.setState({ commissionValue: e })
  }
  // 确认修改佣金比例
  submitEdit = async () => {
    let { id, commissionValue, commissionDataSource } = this.state
    let canEdit = commissionDataSource.filter(item => item.isUpCommissionRate)
    if (canEdit.length > 0) {
      this.setState({ submitLoading: true })
      await editShareCommissionRate({ id, commissionRate: commissionValue }).then(res => {
        if (res.code === 0) {
          message.success('抽佣比例修改成功')
          this.setState({ isEditCommission: false })
        }
        this.setState({ submitLoading: false })
      })
    } else {
      this.setState({ isEditCommission: false })
    }
  }
  //取消修改佣金比例
  cancelEdit = () => {
    this.setState({ isEditCommission: false, commissionValue: null })
  }
  // 导出
  export = () => {
    this.setState({ exportBtnLoading: true }, async () => {
      let tB_data = []
      let res = await sharerAssessList({ ...this.state.queryForm, pageNo: 1, pageSize: -1 })
      if (res.code === 0) {
        tB_data = res.data.data.records.map(item => {
          return {
            ...item,
            orderNumber: item.orderNumber || 0,//下单人数
            gmv: React.$transNum(item.gmv || 0, 2, -2),//订单编号
            commissionRate: item.commissionRate ? item.commissionRate + '%' : '0%',//佣金比例
            updateTime: item.updateTime || '-'
          }
        })
        const option = {
          header: [
            { prop: 'memberId', title: '会员ID', width: 25 },
            { prop: 'username', title: '用户昵称', width: 15 },
            { prop: 'memberMobile', title: '用户会员手机号', width: 15 },
            { prop: 'orderNumber', title: '下单人数', width: 15 },
            { prop: 'gmv', title: 'GMV', width: 15 },
            { prop: 'commissionRate', title: '所生效的佣金比例', width: 15 },
            { prop: 'updateTime', title: '上次修改时间', width: 25 },
          ],
          dataSource: tB_data,
          fileName: '分享官考核列表'
        }
        Json2Excel(option)
      }
    })
    this.setState({ exportBtnLoading: false })
  }
  render() {
    const { columns, dataSource, pageData: { pageNo, pageSize }, total, searchOption, month, exportBtnLoading, isEditCommission, commissionColumns, commissionDataSource, submitLoading } = this.state
    return (
      <div className='p-layout-box'>
        <TheQueryForm
          ref={(ref) => this.queryFormRef = ref}
          option={searchOption}
          show={true}
          onReset={() => this.onReset()}
          onGetValues={(values) => this.onFormSearch(values)} />
        <div style={{ display: 'flex', justifyContent: 'flex-end', marginBottom: 20 }}>
          <TheButton haspermi={['distribution:sharerAssess:export']} size='middle' type='default' onClick={() => { this.export() }} loading={exportBtnLoading}>导出</TheButton>
        </div>
        <Title level={5}>{`分享官月度评级(${month})`}</Title>
        <TheTable
          // scroll={{ x: "max-content", y: '63vh' }}
          columns={columns}
          dataSource={dataSource}
          rowKey={'memberId'}
          onChange={this.handleTableChange}
        />
        <ThePagination pageNo={pageNo} pageSize={pageSize} total={total} pageChange={this.pageChange} />
        <Modal title="佣金修改" visible={isEditCommission} onCancel={() => { this.cancelEdit() }} onOk={this.submitEdit} confirmLoading={submitLoading} destroyOnClose>
          <TheTable
            columns={commissionColumns}
            dataSource={commissionDataSource}
          />
        </Modal >
      </div>
    )
  }
}
